<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore, UserRole } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import { register } from '@/services/userService'

// 获取用户状态管理
const userStore = useUserStore()
const router = useRouter()

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  department: '',
  email: '',
  phone: '',
})

// 动画效果相关
const registerBoxClass = ref('')

/**
 * 组件挂载时的动画效果
 */
onMounted(() => {
  // 添加进入动画类
  setTimeout(() => {
    registerBoxClass.value = 'register-box-show'
  }, 100)
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
}

// 表单引用
const registerFormRef = ref()

// 加载状态
const loading = ref(false)

/**
 * 处理注册表单提交
 */
const handleRegister = async () => {
  // 表单验证
  await registerFormRef.value.validate()

  loading.value = true

  try {
    // 检查是否是管理员用户名（不允许注册管理员）
    if (registerForm.username === userStore.adminAccount.username) {
      ElMessage.error('不能使用管理员用户名进行注册')
      return
    }

    // 调用注册服务
    const user = await register(
      registerForm.username,
      registerForm.password,
      registerForm.name,
      registerForm.department,
      registerForm.email,
      registerForm.phone,
    )

    if (user) {
      // 更新用户状态
      userStore.userInfo = {
        username: user.username,
        role: user.role as UserRole,
      }
      userStore.isLoggedIn = true

      ElMessage.success('注册成功，已自动登录')
      // 注册成功后跳转到用户欢迎页面（普通用户）
      router.push('/user/welcome')
    } else {
      ElMessage.error('注册失败，用户名可能已存在')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="register-container">
    <!-- 背景元素 -->
    <div class="background-elements">
      <div class="mountain mountain-1"></div>
      <div class="mountain mountain-2"></div>
      <div class="mountain mountain-3"></div>
      <div class="cloud cloud-1"></div>
      <div class="cloud cloud-2"></div>
      <div class="cloud cloud-3"></div>
      <div class="rain"></div>
    </div>

    <div class="register-box" :class="registerBoxClass">
      <div class="register-header">
        <h1>巴中市滑坡风险预警系统</h1>
        <p>用户注册</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-position="top"
        class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" placeholder="请输入姓名" prefix-icon="User" />
        </el-form-item>

        <el-form-item label="部门" prop="department">
          <el-input
            v-model="registerForm.department"
            placeholder="请输入部门"
            prefix-icon="Office"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="Message" />
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" prefix-icon="Phone" />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="register-button"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>

        <div class="register-options">
          <el-button link type="primary" @click="goToLogin"> 已有账号？返回登录 </el-button>
        </div>
      </el-form>

      <!-- 管理员提示信息 -->
      <div class="admin-info">
        <p>管理员账号不可注册，请使用登录页面的管理员账号登录</p>
        <p>注册用户将自动设置为普通用户角色</p>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  // 改变背景渐变色，使用更温暖的色调
  background: linear-gradient(135deg, #2c5364, #203a43, #0f2027);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  position: relative;
  overflow: hidden;
}

// 背景动画
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

// 背景元素
.background-elements {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

// 山脉元素 - 调整形状和位置
.mountain {
  position: absolute;
  bottom: 0;
  border-radius: 30% 70% 70% 30% / 30% 30% 70% 70%;
  background: rgba(255, 255, 255, 0.1);
}

.mountain-1 {
  width: 90%;
  height: 70%;
  left: -20%;
  bottom: -45%;
  transform: rotate(-5deg);
}

.mountain-2 {
  width: 70%;
  height: 50%;
  right: -15%;
  bottom: -35%;
  transform: rotate(5deg);
}

.mountain-3 {
  width: 60%;
  height: 40%;
  left: 25%;
  bottom: -25%;
}

// 云朵元素 - 使用不同的动画时间和形状
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 100px;

  &::before,
  &::after {
    content: '';
    position: absolute;
    background: inherit;
    border-radius: 50%;
  }
}

.cloud-1 {
  width: 250px;
  height: 40px;
  top: 15%;
  left: -100px;
  animation: cloud-move 25s linear infinite;

  &::before {
    width: 60px;
    height: 60px;
    top: -30px;
    left: 40px;
  }

  &::after {
    width: 80px;
    height: 80px;
    top: -40px;
    left: 100px;
  }
}

.cloud-2 {
  width: 200px;
  height: 35px;
  top: 35%;
  right: -150px;
  animation: cloud-move 35s linear infinite;

  &::before {
    width: 50px;
    height: 50px;
    top: -25px;
    left: 35px;
  }

  &::after {
    width: 70px;
    height: 70px;
    top: -35px;
    left: 85px;
  }
}

.cloud-3 {
  width: 180px;
  height: 30px;
  top: 25%;
  left: 50%;
  animation: cloud-move 30s linear infinite reverse;

  &::before {
    width: 45px;
    height: 45px;
    top: -22px;
    left: 30px;
  }

  &::after {
    width: 65px;
    height: 65px;
    top: -32px;
    left: 75px;
  }
}

@keyframes cloud-move {
  0% {
    transform: translateX(-100px);
  }

  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

// 替换雨滴效果为星星效果
.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image:
    radial-gradient(2px 2px at 20px 30px, #ffffff, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 40px 70px, #ffffff, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 50px 160px, #ffffff, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 90px 40px, #ffffff, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 130px 80px, #ffffff, rgba(0, 0, 0, 0));
  background-size: 200px 200px;
  animation: stars-move 100s linear infinite;
  opacity: 0.3;
}

@keyframes stars-move {
  from {
    transform: translateY(0);
  }

  to {
    transform: translateY(-200px);
  }
}

// 注册框
.register-box {
  width: 420px; // 稍微宽一些
  padding: 45px;
  border-radius: 20px; // 更圆润的边角
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
  transition: all 0.5s ease;
  z-index: 10;
  opacity: 0;
  transform: translateY(20px);

  &.register-box-show {
    opacity: 1;
    transform: translateY(0);
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow:
      0 15px 30px rgba(0, 0, 0, 0.3),
      0 0 30px rgba(32, 58, 67, 0.2); // 添加柔和的光晕效果
  }
}

.register-header {
  text-align: center;
  margin-bottom: 35px;

  h1 {
    font-size: 26px;
    color: #2c5364;
    margin-bottom: 12px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }

  p {
    font-size: 18px;
    color: #486b79;
    position: relative;
    display: inline-block;
    padding: 0 15px;

    &:before,
    &:after {
      content: '';
      position: absolute;
      width: 30px;
      height: 2px;
      background: #2c5364;
      top: 50%;
    }

    &:before {
      left: -20px;
    }

    &:after {
      right: -20px;
    }
  }
}

.register-form {
  margin-bottom: 25px;

  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px rgba(44, 83, 100, 0.1);

    &:hover {
      box-shadow: 0 0 0 1px rgba(44, 83, 100, 0.2);
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #2c5364;
    }
  }
}

.register-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 10px;
  background: linear-gradient(135deg, #2c5364, #203a43);
  border: none;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(44, 83, 100, 0.3);
    background: linear-gradient(135deg, #203a43, #2c5364);
  }

  &:active {
    transform: translateY(0);
  }
}

.register-options {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;

  :deep(.el-button--link) {
    color: #2c5364;
    font-weight: 500;

    &:hover {
      color: #203a43;
    }
  }
}

.admin-info {
  margin-top: 30px;
  padding: 15px;
  background-color: rgba(44, 83, 100, 0.05);
  border-radius: 10px;
  border-left: 4px solid #2c5364;
  animation: fadeIn 0.5s ease;

  p {
    margin: 5px 0;
    color: #486b79;
    font-size: 14px;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
